import { Client } from "@stomp/stompjs";
import { getToken } from "@/utils/auth";

class WebSocketManager {
  // 订阅主题
  public subscribeToTopic(topic: string, handleSubscribe: (res: any) => void) {
    console.log(`正在订阅主题: ${topic}`);
    const endpoint = import.meta.env.VITE_APP_WS_ENDPOINT;

    // 如果没有配置 WebSocket 端点或显式关闭，直接返回
    if (!endpoint) {
      console.log(
        "WebSocket 已被禁用，如需打开请在配置文件中配置 VITE_APP_WS_ENDPOINT"
      );
      return;
    }

    let stompClient = new Client({
      brokerURL: endpoint,
      heartbeatIncoming: 30000,
      heartbeatOutgoing: 30000,
      connectHeaders: {
        Authorization: getToken(),
      },
      debug: (str: any) => {
        console.info(str);
      },
      onConnect: () => {
        console.info("连接成功");
        stompClient.subscribe(topic, (res: any) => {
          handleSubscribe(res.body);
        });
      },
      onStompError: (frame: any) => {
        console.error("Broker reported error: " + frame.headers["message"]);
        console.error("Additional details: " + frame.body);
      },
      onDisconnect: () => {
        console.info("Websocket 已断开");
      },
    });

    stompClient.activate();
  }

  // 用户点对点
  public subscribeToUser(
    destination: string,
    handleSubscribe: (res: any) => void
  ) {
    const endpoint = import.meta.env.VITE_APP_WS_ENDPOINT;

    // 如果没有配置 WebSocket 端点或显式关闭，直接返回
    if (!endpoint) {
      console.log(
        "WebSocket 已被禁用，如需打开请在配置文件中配置 VITE_APP_WS_ENDPOINT"
      );
      return;
    }

    let stompClient = new Client({
      brokerURL: endpoint,
      heartbeatIncoming: 30000,
      heartbeatOutgoing: 30000,
      connectHeaders: {
        Authorization: getToken(),
      },
      debug: (str: any) => {
        console.info(str);
      },
      onConnect: () => {
        console.info("连接成功");
        let userId = 2;
        stompClient.subscribe(`/user/${userId}${destination}`, (res: any) => {
          handleSubscribe(res.body);
        });
      },
      onStompError: (frame: any) => {
        console.error("Broker reported error: " + frame.headers["message"]);
        console.error("Additional details: " + frame.body);
      },
      onDisconnect: () => {
        console.info("Websocket 已断开");
      },
    });

    stompClient.activate();
  }
}

export default new WebSocketManager();
